package tech.anzhen.simple.rpc.support.rest;


import tech.anzhen.simple.rpc.support.exception.RemoteException;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

public class RestClientInvocationHandler implements InvocationHandler {

    private static final List<Method> METHODS = Arrays.asList(Object.class.getMethods());

    private Object o = new Object();

    private RestClient restClient;

    private String baseAddress;

    public RestClientInvocationHandler(RestClient restClient, String baseAddress) {
        this.restClient = restClient;
        this.baseAddress = baseAddress;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {

        // Object.class内置函数不处理
        if (METHODS.contains(method)) {
            return method.invoke(o, args);
        }

        String name = method.getName();
        if (args != null && args.length > 1) {
            throw new RestException("参数总数不能大于1");
        }
        Object param = null;
        if (args != null && args.length > 0) {
            param = args[0];
        }

        String url = baseAddress + name;

        if (method.getReturnType().getName().equals("void")) {

        }

        Object o = restClient.execute(url, param, method.getGenericReturnType());
        if (o == null && isPrimitive(method.getReturnType())) {
            throw new RemoteException("对于基本类型" + method.getReturnType().getName() + "返回了null");
        }
        return o;
    }

    private boolean isPrimitive(Class<?> clazz) {
        String name = clazz.getName();
        if ("long".equals(name)) {
            return true;
        } else if ("int".equals(name)) {
            return true;
        } else if ("boolean".equals(name)) {
            return true;
        } else if ("short".equals(name)) {
            return true;
        } else if ("byte".equals(name)) {
            return true;
        } else if ("float".equals(name)) {
            return true;
        } else if ("double".equals(name)) {
            return true;
        } else if ("char".equals(name)) {
            return true;
        }
        return false;
    }
}
